package com.link.base.base.pageupload.service;

import com.link.base.base.pageupload.dao.mybatis.mapper.ChunkMapper;
import com.link.base.base.pageupload.model.Chunk;
import com.link.base.base.pageupload.utils.FileUtils;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.DateUtil;
import com.link.core.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * 大文件分片上传service
 * @author 许博文
 * @date 2019/12/25
 */
@Service
public class ChunkServiceImpl extends BasicServiceImpl<Chunk> implements ChunkService {

    private static final Logger logger = LogManager.getLogger(ChunkServiceImpl.class);

    @Resource
    private ChunkMapper chunkMapper;

    @Override
    public BasicMapper<Chunk> getBasicMapper() {
        return chunkMapper;
    }

    @Override
    public boolean checkChunk(Chunk chunk) throws Exception {
        //1.查找该identifier，以及chunkNumber下是否已经有数据，防止并发上传造成数据块重复
        chunk.setPageFlag(false);
        List<Chunk> chunks = chunkMapper.queryByExamplePage(chunk);
        if (chunks.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public void upload(Chunk chunk) throws Exception {
        CoreUser user = UserUtil.getUser();
        String realativPath = "/web/bigfile/" + user.getId() + "/" + DateUtil.dateToStr(new Date(), "yyyyMMdd");
        String realPath = YmlConstants.getPortalShareFileDir() + realativPath;

        MultipartFile file = chunk.getFile();
        logger.info("file originName: {}, chunkNumber: {}" + file.getOriginalFilename() + " ----   " + chunk.getChunkNumber());

        byte[] bytes = file.getBytes();
        Path path = Paths.get(FileUtils.generatePath(realPath, chunk));
        //文件写入指定路径
        Files.write(path, bytes);
        logger.info("文件 {} 写入成功, uuid:{}" + chunk.getFileName() + " -----  " + chunk.getIdentifier());
    }

}
